import { useRequest } from 'ahooks';
import { Button, Cascader, Col, DatePicker, Form, Input, message, Modal, Row, Select, Space } from 'antd';
import React, { useEffect, useState } from 'react';
import provice from '../../../util/place';
import * as APIS from '../../../constants/api-constants';
import moment from 'moment';

const { Option } = Select;
const options = provice;

interface DetailProps {
  showDetail: boolean,
  update: number,
  currentCompanyUuid: string | undefined;
  setShowDetail: (showDetail: boolean) => void
  setFresh: () => void
}

/**
 * 详情查看
 */
export default ({ showDetail, setShowDetail, currentCompanyUuid, update, setFresh }: DetailProps) => {
  const [form] = Form.useForm();
  const [touristForm] = Form.useForm();
  const [medicalFieldList, setMedicalFieldList] = useState<CM.OptionItem[]>();
  const [businessList, setBusinessList] = useState<CM.OptionItem[]>();
  const [type, setTypeList] = useState<CM.OptionItem[]>();

  /**
   * 获取医疗领域和经营方向数组
   */
  const { run: requestOptionList, loading: reqLoading } = useRequest(() => {
    return {
      url: APIS.GET_COMPANY_OPTION_LIST,
      method: 'GET',
    };
  }, {
    manual: true,
    onSuccess: (result) => {
      const { medicalOptionList, businessOptionList, typeList } = result.data.mainData;
      setBusinessList(businessOptionList);
      setMedicalFieldList(medicalOptionList);
      setTypeList(typeList);
    },
    onError: () => {
      message.error('服务器异常，请稍后再试');
      console.log('onError');
    },
  });
  /**
   * 获取当前展示的 company
   */
  const { run: requestCompantDetail, loading: req2Loading } = useRequest((uuid) => {
    return {
      url: APIS.GET_COMPANY_DETAIL,
      method: 'GET',
      params: {
        uuid
      },
    };
  }, {
    manual: true,
    onSuccess: (result) => {
      const company = result.data.mainData;
      console.log(company);
      const ad = company.address.split(';');
      company.addressBefore = [ad[0], ad[1], ad[2]];
      company.address = ad[3];
      company.createDate = moment(new Date(company.createTime));
      company.mainBusiness = company.MainBusinesses.map((item: any) => item.uuid);
      company.updateTime = moment(new Date(company.updateTime))
        .format('YYYY-MM-DD HH:mm:ss');


      form.setFieldsValue(company);
      touristForm.setFieldsValue(company);
    },
    onError: () => {
      message.error('服务器异常，请稍后再试');
      console.log('onError');
    },
  });

  /**
   * 修改企业
   */
  const { run: updateCompany, loading } = useRequest((e) => {
    return {
      url: APIS.UPDATE_COMPANY,
      method: 'POST',
      data: {
        ...e,
        uuid: currentCompanyUuid
      }
    };
  }, {
    manual: true,
    onSuccess: (res) => {
      if (res.data.mainData.success) {
        message.success('修改成功');
        setShowDetail(false);
        setFresh();
      } else {
        message.error('服务器异常，请稍后再试');
      }
    },
    onError: () => {
      message.error('服务器异常，请稍后再试');
      console.log('onError');
    },
  });


  useEffect(() => {
    if (currentCompanyUuid) {
      requestOptionList();
      requestCompantDetail(currentCompanyUuid);/* .then(() => {
        form.setFieldsValue(currentCompanyDetail
        );
      }); */
    }
  }, [currentCompanyUuid, requestCompantDetail, requestOptionList, update]);

  return (
    <>
      <Modal
        visible={showDetail}
        title="企业详细信息"
        destroyOnClose={true}
        onCancel={() => {
          setShowDetail(false);
        }}
        footer={null}
        width={'70vw'}
        style={{ top: 15 }}
      >
        {window.localStorage.getItem('identity') === null ?
          <Form
            layout="horizontal"
            labelAlign="right"
            colon={true}
            form={touristForm}
            preserve={false}
          >
            <Row style={{ width: '100%' }}>
              <Col span={24}>
                <Form.Item
                  name="description"
                  label="企业简介"
                  rules={[{ required: true, message: '企业简介不能为空' }]}
                >
                  <Input.TextArea
                    maxLength={300}
                    rows={4}
                    placeholder='企业简介(限制在300字之内)'
                    style={{ resize: 'none' }}
                  />
                </Form.Item>
              </Col>
            </Row>
          </Form>
          :
          <Form
            layout="horizontal"
            labelAlign="right"
            colon={true}
            form={form}
            preserve={false}
            onFinish={(e) => {
              e.createDate = e.createDate.format('YYYY-MM-DD kk:mm:ss');
              updateCompany(e);
            }}
          >
            <Row justify="space-between" gutter={24}>
              <Col span={12}>
                <Form.Item
                  label="企业名称"
                  name="name"
                  rules={[{ required: true, message: '企业名称不能为空' }]}
                >
                  <Input/>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="组织机构代码"
                  name="companyNum"
                >
                  <Input placeholder="请输入组织机构代码"/>
                </Form.Item>
              </Col>
            </Row>
            <Row justify="space-between" gutter={24}>
              <Col span={12}>
                <Form.Item
                  name="addressBefore"
                  label="所在城市"
                  rules={[{ required: true, message: '所在城市不能为空' }]}
                >
                  <Cascader options={options} placeholder="请输入企业所在的城市"/>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="具体街道"
                  name="address"
                >
                  <Input/>
                </Form.Item>
              </Col>
            </Row>
            <Row justify="space-between" gutter={24}>
              <Col span={8}>
                <Form.Item
                  label="医疗领域"
                  labelAlign="right"
                  name="medicalField"
                  rules={[{ required: true, message: '医疗领域不能为空！' }]}
                >
                  <Select
                    style={{ width: '100%' }}
                  >
                    {
                      medicalFieldList?.map((item) => {
                        return (
                          <Option key={item.uuid} value={item.uuid}>{item.name}</Option>
                        );
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="企业类型"
                  labelAlign="right"
                  name="type"
                  rules={[{ required: true, message: '企业类型不能为空！' }]}
                >
                  <Select
                    style={{ width: '100%' }}
                  >
                    {
                      type?.map((item) => {
                        return (
                          <Option key={item.uuid} value={item.uuid}>{item.name}</Option>
                        );
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="成立时间"
                  labelAlign="right"
                  name="createDate"
                >
                  <DatePicker/>
                </Form.Item>
              </Col>
            </Row>
            <Row justify="space-between">
              <Col span={24}>
                <Form.Item
                  label="主营业务"
                  name="mainBusiness"
                  rules={[{ required: true, message: '主营业务不能为空' }]}
                >
                  <Select
                    mode="multiple"
                    allowClear
                    style={{ width: '100%' }}
                    placeholder="请选择主营业务"
                    onChange={() => {
                    }}
                  >
                    {
                      businessList?.map((item) => {
                        return (
                          <Option key={item.uuid} value={item.uuid}>{item.name}</Option>
                        );
                      })
                    }
                  </Select>
                </Form.Item>

              </Col>
            </Row>
            <Row style={{ width: '100%' }}>
              <Col span={24}>
                <Form.Item
                  name="description"
                  label="企业简介"
                  rules={[{ required: true, message: '企业简介不能为空' }]}
                >
                  <Input.TextArea
                    maxLength={300}
                    rows={4}
                    placeholder='企业简介(限制在300字之内)'
                    style={{ resize: 'none' }}
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row style={{ width: '100%', marginTop: '10vh' }} align="bottom" gutter={24}>
              <Col span={6}>
                <Form.Item label="录入时间" name="updateTime">
                  <Input disabled/>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item
                  label="填写人"
                  name="filler"
                  rules={[{ required: true, message: '填写人不能为空' }]}
                  initialValue={localStorage.getItem('userName')}
                >
                  <Input readOnly/>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item wrapperCol={{ span: 22 }}>
                  <Space style={{ float: 'right' }}>
                    <Button
                      type="primary"
                      htmlType="submit"
                      loading={loading || (req2Loading && reqLoading)}
                    >
                      确认
                    </Button>
                    <Button
                      type="primary"
                      onClick={() => {
                        setShowDetail(false);
                      }}
                    >
                      返回
                    </Button>
                  </Space>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        }
      </Modal>
    </>
  );
}

